﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NLog;
using SYT.Common.QuartzUtil;
using Topshelf;

namespace SYT.Common.ServiceFactory
{
    public class BaseWinServer : ServiceControl
    {
        private Logger _loger = null;
        private IHostServer _hostServer;
        public event EventHandler OnInit = null;
        public event EventHandler OnStart = null;
        public event EventHandler OnStop = null;

        public BaseWinServer(Logger loger)
        {
            _loger = loger;
        }

        public BaseWinServer(Logger loger, IHostServer hostServer)
        {
            _loger = loger;
            _hostServer = hostServer;
        }

        public void Initialize()
        {
            try
            {
                Quartz.Logging.LogProvider.IsDisabled = true;
                OnInit?.Invoke(this, new ServiceEventArgs(null, _loger));
            }
            catch (Exception ex)
            {
                _loger.Error(ex.Message + Environment.NewLine + ex.StackTrace);
            }
        }

        public bool Start(HostControl hostControl)
        {
            try
            {
                QuartzHelper.Run();
                OnStart?.Invoke(this, new ServiceEventArgs(hostControl,_loger));
                return true;
            }
            catch (Exception ex)
            {
                _loger.Error(ex.Message + Environment.NewLine + ex.StackTrace);
                return false;
            }
        }

        public bool Stop(HostControl hostControl)
        {
            try
            {
                QuartzHelper.Stop();
                OnStop?.Invoke(this, new ServiceEventArgs(hostControl, _loger));
                if (_hostServer != null)
                    _hostServer.Stop();
                return true;
            }
            catch (Exception ex)
            {
                _loger.Error(ex.Message + Environment.NewLine + ex.StackTrace);
                return false;
            }
        }
    }
}
